import * as Calendar from "expo-calendar";

import {
  Alert,
  FlatList,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import React, { useEffect, useState } from "react";

import NetworkLogger from "react-native-network-logger";
// 测试一下请求axios调用four
import apis from "@/services";

function login(data: any) {
  return apis<Response>("/user/pc/login", {
    data,
    method: "post",
  });
}

function loginget(data: any) {
  return apis<Response>("/user/pc/loginget", {
    method: "get",
  });
}

const fetchData = async () => {
  try {
    console.log("fetchData");

    const response = await apis.get("/api/some-endpoint");
    console.log("Data:", response.data);
  } catch (error) {
    console.error("fetchData Error:", error);
  }
};
const CustomCalendar = () => {
  const [events, setEvents] = useState({});
  const [selectedDate, setSelectedDate] = useState(new Date());
  const [newEventTitle, setNewEventTitle] = useState("");

  useEffect(() => {
    const fetchEvents = async () => {
      const granted = await requestCalendarPermission();
      if (!granted) {
        console.log("Calendar permission not granted");
        return;
      }

      const todayEvents = await getEventsForDay(new Date());
      setEvents({ [new Date().toDateString()]: todayEvents });
    };

    fetchEvents();
  }, []);
  const testApi = () => {
    fetchData()
      .then(() => {})
      .catch((err) => {
        console.log("err报错了");
      });
    login(1)
      .then((res) => {
        Alert.alert("axios请求成功");
      })
      .catch((err) => {
        Alert.alert("axios请求错误", err.message);
      });
  };

  const requestCalendarPermission = async () => {
    const { status } = await Calendar.requestCalendarPermissionsAsync();
    console.log("Calendar permission status: ", status);
    return status === "granted";
  };

  const getEventsForDay = async (date) => {
    try {
      const calendars = await Calendar.getCalendarsAsync(
        Calendar.EntityTypes.EVENT
      );
      console.log("Calendars: ", calendars);
      if (!calendars.length) {
        console.log("No calendars found");
        return [];
      }
      const calendarId = calendars[0].id;

      const startDate = new Date(date.setHours(0, 0, 0, 0));
      const endDate = new Date(date.setHours(23, 59, 59, 999));

      const events = await Calendar.getEventsAsync(
        [calendarId],
        startDate,
        endDate
      );
      console.log("Events for the day: ", events);
      return events;
    } catch (error) {
      console.error("Error getting events for day: ", error);
      return [];
    }
  };

  const addEventToCalendar = async (title, date) => {
    try {
      const calendars = await Calendar.getCalendarsAsync(
        Calendar.EntityTypes.EVENT
      );
      console.log("Calendars: ", calendars);
      if (!calendars.length) {
        console.log("No calendars found");
        return;
      }
      const calendarId = calendars[0].id;

      const event = await Calendar.createEventAsync(calendarId, {
        title,
        startDate: date,
        endDate: new Date(date.getTime() + 60 * 60 * 1000), // Default duration of 1 hour
        timeZone: "GMT",
        location: "Unknown",
      });
      console.log("Event created: ", event);
      return event;
    } catch (error) {
      console.error("Error adding event to calendar: ", error);
      return null;
    }
  };

  const handleDatePress = async (date) => {
    const dayEvents = await getEventsForDay(date);
    setEvents({ ...events, [date.toDateString()]: dayEvents });
    setSelectedDate(date);
  };

  const handleAddEvent = async () => {
    if (!newEventTitle) {
      Alert.alert("Please enter a title for the event.");
      return;
    }
    const event = await addEventToCalendar(newEventTitle, selectedDate);
    if (event) {
      const updatedEvents = await getEventsForDay(selectedDate);
      setEvents({ ...events, [selectedDate.toDateString()]: updatedEvents });
      setNewEventTitle("");
    }
  };

  const renderEvent = ({ item }) => (
    <View style={styles.eventContainer}>
      <Text style={styles.eventTitle}>{item.title}</Text>
      <Text style={styles.eventTime}>
        {new Date(item.startDate).toLocaleTimeString()} -{" "}
        {new Date(item.endDate).toLocaleTimeString()}
      </Text>
    </View>
  );

  const renderDay = (day) => (
    <TouchableOpacity
      key={day}
      style={[
        styles.dayContainer,
        selectedDate.getDate() === day &&
          selectedDate.getMonth() === new Date().getMonth() &&
          styles.selectedDay,
      ]}
      onPress={() =>
        handleDatePress(
          new Date(selectedDate.getFullYear(), selectedDate.getMonth(), day)
        )
      }
    >
      <Text style={styles.dayText}>{day}</Text>
    </TouchableOpacity>
  );

  const daysInMonth = new Date(
    selectedDate.getFullYear(),
    selectedDate.getMonth() + 1,
    0
  ).getDate();

  const handlePrevMonth = () => {
    const prevMonth = new Date(
      selectedDate.getFullYear(),
      selectedDate.getMonth() - 1,
      1
    );
    setSelectedDate(prevMonth);
  };

  const handleNextMonth = () => {
    const nextMonth = new Date(
      selectedDate.getFullYear(),
      selectedDate.getMonth() + 1,
      1
    );
    setSelectedDate(nextMonth);
  };

  const handlePrevYear = () => {
    const prevYear = new Date(
      selectedDate.getFullYear() - 1,
      selectedDate.getMonth(),
      1
    );
    setSelectedDate(prevYear);
  };

  const handleNextYear = () => {
    const nextYear = new Date(
      selectedDate.getFullYear() + 1,
      selectedDate.getMonth(),
      1
    );
    setSelectedDate(nextYear);
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity onPress={handlePrevYear}>
          <Text style={styles.changeMonthText}>{"<<"}</Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={handlePrevMonth}>
          <Text style={styles.changeMonthText}>{"<"}</Text>
        </TouchableOpacity>
        <Text style={styles.monthText}>
          {selectedDate.toLocaleString("default", {
            year: "numeric",
            month: "long",
          })}
        </Text>
        <TouchableOpacity onPress={handleNextMonth}>
          <Text style={styles.changeMonthText}>{">"}</Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={handleNextYear}>
          <Text style={styles.changeMonthText}>{">>"}</Text>
        </TouchableOpacity>
      </View>
      <View style={styles.calendar}>
        {[...Array(daysInMonth).keys()].map((_, index) => renderDay(index + 1))}
      </View>
      <FlatList
        data={events[selectedDate.toDateString()] || []}
        keyExtractor={(item) => item.id}
        renderItem={renderEvent}
        style={styles.list}
      />
      <View style={styles.addEventContainer}>
        {/* <TextInput
          style={styles.input}
          placeholder="New event title"
          value={newEventTitle}
          onChangeText={setNewEventTitle}
        />
        <TouchableOpacity style={styles.addButton} onPress={handleAddEvent}>
          <Text style={styles.addButtonText}>Add Event</Text>
        </TouchableOpacity> */}
        <TouchableOpacity style={styles.addButton} onPress={testApi}>
          <Text style={styles.addButtonText}>TestAPI</Text>
        </TouchableOpacity>
        <NetworkLogger />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
  },
  header: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 10,
  },
  changeMonthText: {
    fontSize: 18,
    fontWeight: "bold",
  },
  monthText: {
    fontSize: 18,
    fontWeight: "bold",
  },
  calendar: {
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "space-between",
  },
  dayContainer: {
    width: "14%",
    alignItems: "center",
    marginVertical: 10,
  },
  selectedDay: {
    backgroundColor: "#007BFF",
    borderRadius: 5,
  },
  dayText: {
    fontSize: 18,
    color: "#333",
  },
  list: {
    marginTop: 20,
  },
  eventContainer: {
    marginBottom: 10,
    padding: 10,
    backgroundColor: "#f9f9f9",
    borderRadius: 5,
    borderColor: "#ccc",
    borderWidth: 1,
  },
  eventTitle: {
    fontSize: 16,
  },
  eventTime: {
    fontSize: 14,
    color: "#888",
  },
  addEventContainer: {
    flexDirection: "row",
    alignItems: "center",
    marginTop: 20,
  },
  input: {
    flex: 1,
    borderColor: "#ccc",
    borderWidth: 1,
    borderRadius: 5,
    padding: 10,
    marginRight: 10,
  },
  addButton: {
    backgroundColor: "#007BFF",
    padding: 10,
    borderRadius: 5,
  },
  addButtonText: {
    color: "#fff",
    fontSize: 14,
  },
});

export default CustomCalendar;
